package com.example.heipictureserver.mangger.upload;

import cn.hutool.core.io.FileUtil;
import com.example.heipictureserver.exception.BusinessException;
import com.example.heipictureserver.exception.ErrorCode;
import com.example.heipictureserver.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/*
  *@Description 文件上传
  *@Author bwg
  *@Date 2025/1/23 21:57
*/
@Service
public class FilePictureUpload extends PictureUploadTemplate {


 private static final long OneMb = 1024 * 1024;

 private static final long MAX_SIZE = 5 * OneMb;
 @Override
 protected void processFile(Object inputSource, File file) {
  MultipartFile multipartFile = (MultipartFile) inputSource;
     try {
         multipartFile.transferTo(file);
     } catch (IOException e) {
      throw  new BusinessException(ErrorCode.PARAMS_ERROR, "文件处理失败");
     }
 }

 @Override
 protected void validPicture(Object inputSource) {
  MultipartFile multipartFile = (MultipartFile) inputSource;
  ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
  // 1. 校验文件大小
  long fileSize = multipartFile.getSize();
  ThrowUtils.throwIf(fileSize > MAX_SIZE, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2MB");
  // 2. 校验文件后缀
  String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
  // 允许上传的文件后缀列表（或者集合）
  final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "png", "jpg", "webp");
     if (fileSuffix != null) {
         ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix.toLowerCase()), ErrorCode.PARAMS_ERROR, "文件类型错误");
     }
 }

 @Override
 protected String getOriginalFilename(Object inputSource) {
  MultipartFile multipartFile = (MultipartFile) inputSource;
  return multipartFile.getOriginalFilename();
 }
}
